<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
    <meta charset="UTF-8">
    <title>角色管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <link rel="icon" href="/favicon.ico">
    <link rel="stylesheet" href="/resources/layui/css/layui.css" media="all"/>
    <link rel="stylesheet" href="/resources/css/public.css" media="all"/>
    <link rel="stylesheet" href="/resources/layui_ext/dtree/dtree.css" media="all"/>
    <link rel="stylesheet" href="/resources/layui_ext/dtree/font/dtreefont.css" media="all"/>
</head>
<body class="childrenBody">
<!-- 查询条件开始-->
<form class="layui-form">
    <blockquote class="layui-elem-quote quoteBox">
        <form class="layui-form">
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">角色编码</label>
                    <div class="layui-input-inline">
                        <input type="text" name="rolecode" id="rolecode" class="layui-input searchVal"
                               placeholder="请输入角色编码"/>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">角色名称</label>
                    <div class="layui-input-inline">
                        <input type="text" name="rolename" id="rolename" class="layui-input searchVal"
                               placeholder="请输入角色名称"/>
                    </div>
                </div>
                <div class="layui-inline">
                    <button type="button" class="layui-btn" lay-submit lay-filter="doSearch" shiro:hasPermission="role:view"><span
                            class="layui-icon layui-icon-search"></span>查询
                    </button>
                    <button type="reset" class="layui-btn layui-btn-warm"><span
                            class="layui-icon layui-icon-refresh-1"></span>重置
                    </button>
                </div>
            </div>
        </form>
    </blockquote>
</form>
<!-- 查询条件结束-->


<!-- 数据表格开始 -->
<div>
    <table class="layui-hide" id="roleTable" lay-filter="roleTable"></table>
    <!-- 工具栏 -->
    <div id="roleToolBar" style="display: none;">
        <button type="button" lay-event="add" class="layui-btn layui-btn-sm" shiro:hasPermission="role:create"><span
                class="layui-icon layui-icon-add-1"></span>添加角色
        </button>
    </div>

    <div id="roleRowBar" style="display: none;">
        <button type="button" lay-event="update" class="layui-btn layui-btn-sm" shiro:hasPermission="role:update"><span
                class="layui-icon layui-icon-edit"></span>更新
        </button>
        <button type="button" lay-event="delete" class="layui-btn layui-btn-sm layui-btn-danger" shiro:hasPermission="role:delete">
            <span class="layui-icon layui-icon-delete"></span>删除
        </button>
        <button type="button" lay-event="selectRolePermission" class="layui-btn layui-btn-sm" shiro:hasPermission="role:selectPermission">
            <span class="layui-icon layui-icon-about"></span>分配权限
        </button>
    </div>
</div>
<!-- 数据表格结束 -->

<!-- 添加和修改的弹出层开始 -->
<div style="display: none;padding: 5px" id="addOrUpdateDiv">
    <form class="layui-form" style="width:80%;margin-top: 20px;" id="dataFrm" lay-filter="dataFrm">
        <!-- 隐藏域，保存角色id -->
        <input type="hidden" name="id">
        <div class="layui-form-item layui-row layui-col-xs12">
            <label class="layui-form-label">角色编码</label>
            <div class="layui-input-block">
                <input type="text" class="layui-input" name="rolecode" lay-verify="required" placeholder="请输入角色编码">
            </div>
        </div>
        <div class="layui-form-item layui-row layui-col-xs12">
            <label class="layui-form-label">角色名称</label>
            <div class="layui-input-block">
                <input type="text" class="layui-input" name="rolename" lay-verify="required" placeholder="请输入角色名称">
            </div>
        </div>
        <div class="layui-form-item layui-row layui-col-xs12">
            <label class="layui-form-label">角色备注</label>
            <div class="layui-input-block">
                <textarea placeholder="请输入角色备注" name="remark" id="remark" class="layui-textarea userDesc"></textarea>
            </div>
        </div>
        <div class="layui-form-item layui-row layui-col-xs12">
            <div class="layui-input-block" style="text-align: center;">
                <button type="button" class="layui-btn" lay-submit lay-filter="doSubmit"><span
                        class="layui-icon layui-icon-add-1"></span>提交
                </button>
                <button type="reset" class="layui-btn layui-btn-warm"><span
                        class="layui-icon layui-icon-refresh-1"></span>重置
                </button>
            </div>
        </div>
    </form>
</div>
<!-- 添加和修改的弹出层结束 -->

<!-- 分配权限的弹出层 开始 -->
<div style="display: none;" id="selectRolePermissionDiv">
    <ul id="permissionTree" class="dtree" data-id="0"></ul>
</div>
<!-- 分配权限的弹出层 结束-->


<script type="text/javascript" src="/resources/layui/layui.js"></script>
<script type="text/javascript">
    layui.extend({
        dtree: '/resources/layui_ext/dtree/dtree'   // {/}的意思即代表采用自有路径，即不跟随 base 路径
    }).use(['jquery', 'form', 'table', 'layer', 'dtree'], function () {
        var $ = layui.jquery;
        var form = layui.form;
        var table = layui.table;
        var layer = layui.layer;
        var dtree = layui.dtree;


        //渲染数据表格
        var tableIns = table.render({
            elem: '#roleTable'//绑定表格组件的id元素
            , url: '/sys/role/rolelist'//数据发送的请求路径
            , toolbar: '#roleToolBar' //开启头部工具栏，并为其绑定左侧模板
            , title: '角色数据表'
            , height: 'full-110'
            , page: true
            , cols: [
                [
                {type: 'checkbox', fixed: 'left'}
                , {field: 'id', title: 'ID', align: 'center', width: 60}
                , {field: 'rolecode', title: '角色编码', align: 'center'}
                , {field: 'rolename', title: '角色名称', align: 'center'}
                , {field: 'createtime', title: '创建时间', align: 'center'}
                , {field: 'remark', title: '备注', align: 'center'}
                , {field: 'right', title: '操作', align: 'center', toolbar: "#roleRowBar", width: 300}
                ]
            ]
            //回调函数
            , done: function (res, curr, count) {
                // 判断当前页码是否大于1
                if (curr > 1 && res.data.length == 0) {
                    //当前页码-1
                    var pageValue = curr - 1;
                    tableIns.reload({
                        page: {curr: pageValue}// 修改页码
                    })
                }
            }
        });


        //模糊查询
        form.on("submit(doSearch)", function (data) {
            tableIns.reload({
                where: data.field,
                page: {
                    curr: 1
                }
            });
        });

        //监听头部工具栏事件
        table.on("toolbar(roleTable)", function (obj) {
            switch (obj.event) {
                case "add":
                    openAddRoleWindow();
                    break;
            }
        });

        //弹出层索引，提交路径
        var mainIndex, url;

        /**
         * 打开添加角色窗口
         */
        function openAddRoleWindow() {
            mainIndex = layer.open({
                type: 1,
                title: "添加角色",
                area: ["800px", "500px"],
                content: $("#addOrUpdateDiv"),//引用的内容窗口
                success: function () {
                    //清空表单数据
                    $("#dataFrm")[0].reset();
                    //添加的提交请求
                    url = "/sys/role/addRole";
                }
            });
        }


        //监听表单提交按钮（添加菜单和修改菜单）
        form.on("submit(doSubmit)", function (data) {
            $.post(url, data.field, function (result) {
                if (result.success) {
                    //刷新数据表格
                    tableIns.reload();
                }
                //显示提示信息
                layer.msg(result.message);
                //关闭当前窗口
                layer.close(mainIndex);
            }, "json");

            return false;
        });

        //监听行工具栏事件
        table.on("tool(roleTable)", function (obj) {
            switch (obj.event) {
                case 'update':
                    openUpdateRoleWindow(obj.data);
                    break;
                case 'delete':
                    //删除角色
                    deleteRole(obj.data);
                    break;
                case 'selectRolePermission':
                    //分配权限
                    selectRolePermission(obj.data);
                    break;
            }
        });

        /**
         * 修改角色
         * @param data
         */
        function openUpdateRoleWindow(data) {
            mainIndex = layer.open({
                type: 1,
                title: "更新角色",
                area: ["800px", "500px"],
                content: $("#addOrUpdateDiv"),//引用的内容窗口
                success: function () {
                    //表单数据回显
                    form.val("dataFrm", data);
                    //添加的提交请求
                    url = "/sys/role/updateRole";
                }
            });
        }

        /**
         * 删除角色
         * @param data
         */
        function deleteRole(data) {
            layer.confirm("确定要删除这条数据吗?", {"icon": 3, "title": "提示"}, function (index) {
                $.post("/sys/role/deleteById", {"id": data.id}, function (result) {
                    if (result.success) {
                        //刷新数据表格
                        tableIns.reload();
                    }
                    //显示提示信息
                    layer.msg(result.message);
                }, "json");
                //关闭弹框
                layer.close(index);
            })
        }

        /**
         * 分配权限
         * @param data
         */
        function selectRolePermission(data) {
            mainIndex = layer.open({
                type: 1,
                title: "分配[" + data.rolename + "]权限",
                area: ["400px", "450px"],
                content: $("#selectRolePermissionDiv"),//引用的内容窗口
                btn: ['<span class="layui-icon layui-icon-ok">确定</span>', '<span class="layui-icon layui-icon-close">取消</span>'],
                yes: function (index, layero) {
                    //按钮【按钮一】的回调
                    //监听树节点的选中事件
                    var permissionData = dtree.getCheckbarNodesParam("permissionTree");
                    //声明数组对象
                    var idArr = [];
                    //循环遍历选中的节点id
                    for (var i = 0; i < permissionData.length; i++) {
                        //nodeId是当前选中的节点Id
                        idArr.push(permissionData[i].nodeId);
                    }
                    //使用join()方法转成字符串
                    var ids = idArr.join(",");//权限节点ID
                    //判断是否有选中树节点
                    if (ids.length != 0) {
                        //rid:是当前要分配权限的角色ID，ids:是选中的权限树节点id
                        $.post("/sys/role/saveRolePermission", {"ids": ids, "rid": data.id}, function (result) {
                            layer.msg(result.message);
                        }, "json");
                    } else {
                        layer.msg("请选择要分配的权限！");
                    }
                },
                btn2: function (index, layero) {
                    //按钮【按钮二】的回调
                    //return false 开启该代码可禁止点击该按钮关闭
                },
                success: function () {
                    //加载菜单树
                    dtree.render({
                        elem: "#permissionTree",
                        url: "/sys/role/initPermissionByRoleId?roleId=" + data.id,
                        dataStyle: "layuiStyle",  //使用layui风格的数据格式
                        response: {message: "msg", statusCode: 0},  //修改response中返回数据的定义
                        dataFormat: "list",
                        checkbar: true,
                        checkbarType: "all" // 默认就是all，其他的值为： no-all  p-casc   self  only
                    });
                }
            });
        }

    });
</script>
</body>
</html>